<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据可视化</title>

    <link rel="stylesheet" th:href="@{/css/semantic.css}" />
    <link rel="stylesheet" th:href="@{/css/index.css}" />
    <link rel="stylesheet" th:href="@{/css/index.less}" />

    <script th:src="@{/js/echarts.min.js}"></script>
    <script th:src="@{/js/jquery-3.5.1.min.js}"></script>
    <script th:src="@{/js/time.js}"></script>
</head>
<body>
    <header>
        <h1>农产品价格分析统计--土豆</h1>
        <div class="showTime"></div>
    </header>
    <section class="mainbox">

        <div class="column">
            <div class="panel bar">
                <h2 th:text="${province + '地区2018年~2021年的价格数据'}">某地区2018年~2021年的价格数据</h2>
                <div class="chart"></div>
                <div class="panel-footer"></div>
            </div> 
            <div class="panel line">
                <h2 th:text="${year + '一年内所有省份价格变化动态图'}">某年所有省份价格变化</h2>
                <div class="chart"></div>
                <div class="panel-footer"></div>
            </div>
        </div>

        <div class="column">
            <div class="no">
                <div class="no-hd">
                    <ul>
                        <li th:text="${maxValue}">最大值</li>
                        <li th:text="${minValue}">最小值</li>
                    </ul>
                </div>
                <div class="no-bd">
                    <ul>
                        <li>最高价格</li>
                        <li>最低价格</li>
                    </ul>
                </div>
            </div>
            <div class="map">
                <div class="map1"></div>
                <div class="map2"></div>
                <div class="map3"></div>
                <div class="chart">地图模块</div>
            </div>
        </div>

        <div class="column">
            <div class="panel bar2">
                <h2 th:text="${province + year + '年的所有月份数据'}">某地区某年的所有月份数据</h2>
                <div class="chart"></div>
                <div class="panel-footer"></div>
            </div>
            <div class="panel line2">
                <h2 th:text="${year + '年所有省份平均价格统计'}">某年所有省份平均价格统计</h2>
                <div class="chart"></div>
                <div class="panel-footer"></div>
            </div>
        </div>
    </section>
    <script src="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.js"></script>
    <script th:src="@{/js/china.js}"></script>
    <script th:src="@{/js/flexible.js}"></script>
    <!--    <script th:src="@{/js/index.js}"></script>-->
    <!--    <script th:src="@{/js/Map.js}"></script>-->
    <!--    地图样式-->
    <script th:inline="javascript">
        /*<![CDATA[*/
        var priceDataList = /*[[${priceDataList}]]*/ [];

        (function () {
            var myChart = echarts.init(document.querySelector('.map .chart'));

            var mapName = 'china'
            var data = priceDataList.map(priceData => ({
                name: priceData.province,
                value: priceData.averagePrice,
            }));
            var geoCoordMap = {};

            // Rest of your code here...
            /*获取地图数据*/
            myChart.showLoading();
            var mapFeatures = echarts.getMap(mapName).geoJson.features;
            myChart.hideLoading();
            mapFeatures.forEach(function(v) {
                // 地区名称
                var name = v.properties.name;
                // 地区经纬度
                geoCoordMap[name] = v.properties.cp;

            });

            console.log(data)
            var max = 480,
                min = 9; //
            var maxSize4Pin = 100,
                minSize4Pin = 20;

            var convertData = function(data) {
                var res = [];
                for (var i = 0; i < data.length; i++) {
                    if (data[i].name == '黑龙')
                        data[i].name = '黑龙江'
                    if (data[i].name == '内蒙')
                        data[i].name = '内蒙古'
                    var geoCoord = geoCoordMap[data[i].name];
                    if (geoCoord) {
                        res.push({
                            name: data[i].name,
                            value: geoCoord.concat(data[i].value),
                        });
                    }
                }
                return res;
            };
            option = {

                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        if (typeof(params.value)[2] == "undefined") {
                            var toolTiphtml = ''
                            for(var i = 0;i<data.length;i++){
                                if(params.name == data[i].name){
                                    toolTiphtml += data[i].name+':'+ data[i].value
                                }
                            }
                            console.log(toolTiphtml)
                            // console.log(convertData(data))
                            return toolTiphtml;
                        } else {
                            var toolTiphtml = ''
                            for(var i = 0;i<data.length;i++){
                                if(params.name == data[i].name){
                                    toolTiphtml += data[i].name+':'+ data[i].value
                                }
                            }
                            console.log(toolTiphtml)
                            return toolTiphtml;
                        }
                    }
                },
                visualMap: {
                    show: true,
                    min: 0,
                    max: 200,
                    left: 'left',
                    top: 'bottom',
                    text: ['高', '低'], // 文本，默认为数值文本
                    calculable: true,
                    seriesIndex: [1],
                    inRange: {
                        color: ['#e6f7ff', '#1890FF','#0050b3'] // 渐变颜色
                    }
                },
                geo: {
                    show: true,
                    map: mapName,
                    label: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false,
                        }
                    },
                    roam: false,
                    itemStyle: {
                        normal: {
                            areaColor: 'rgba(20,41,87,0.8)',
                            borderColor: '#195bb9',
                        },
                        emphasis: {
                            areaColor: '#2B91B7',
                        }
                    }
                },
                series: [{
                    name: '散点',
                    type: 'scatter',
                    coordinateSystem: 'geo',
                    data: convertData(data),
                    symbolSize: function(val) {
                        return val[2] / 10;
                    },
                    label: {
                        normal: {
                            formatter: '{b}',
                            position: 'right',
                            show: true
                        },
                        emphasis: {
                            show: true
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: '#05C3F9'
                        }
                    }
                },
                    {
                        type: 'map',
                        map: mapName,
                        geoIndex: 0,
                        aspectScale: 0.75, //长宽比
                        showLegendSymbol: false, // 存在legend时显示
                        label: {
                            normal: {
                                show: true
                            },
                            emphasis: {
                                show: false,
                                textStyle: {
                                    color: '#fff'
                                }
                            }
                        },
                        roam: true,
                        itemStyle: {
                            normal: {
                                areaColor: '#031525',
                                borderColor: '#3B5077',
                            },
                            emphasis: {
                                areaColor: '#2B91B7'
                            }
                        },
                        animation: false,
                        data: data
                    },
                    {
                        name: 'Top 5',
                        type: 'effectScatter',
                        coordinateSystem: 'geo',
                        data: convertData(data.sort(function(a, b) {
                            return b.value - a.value;
                        }).slice(0, 5)),
                        symbolSize: function(val) {
                            return val[2] / 10;
                        },
                        showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke'
                        },
                        hoverAnimation: true,
                        label: {
                            normal: {
                                formatter: '{b}',
                                position: 'right',
                                show: true
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: 'yellow',
                                shadowBlur: 10,
                                shadowColor: 'yellow'
                            }
                        },
                        zlevel: 1
                    },

                ]
            };
            myChart.setOption(option);
            window.addEventListener('resize',function(){
                myChart.resize();
            });
        })();
        /*]]>*/
    </script>

    <!--    某地区2018年~2021年价格数据展示-->
    <script th:inline="javascript">
        /*<![CDATA[*/
        var province = /*[[${province}]]*/

        $(document).ready(function() {
            // $('.ui.dropdown').dropdown();
            // // 处理标签选择事件
            // $('.ui.menu .item').on('click', function() {
            //     var selectedTag = $(this).text().substring(0, 2);
            //     console.log("Selected tag: " + selectedTag);
            //
            //     // 插入你的文章过滤逻辑代码
            // });
            $.ajax({
                url: "/data/province/years/months",
                method: "GET",
                data: { province: province }, // 替换为你的省份
                success: function(data) {
                    var priceDataMap = data;
                    var myChart = echarts.init(document.querySelector('.bar .chart'), 'dark');
                    var option = {
                        tooltip: {
                            trigger: 'axis',
                        },
                        legend: {
                            data: Object.keys(priceDataMap),
                        },
                        xAxis: {
                            type: 'category',
                            data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
                            axisLabel: {
                                textStyle: {
                                    color: '#87CEFA' // 亮蓝色字体
                                }
                            }
                        },
                        yAxis: {
                            type: 'value',
                            axisLabel: {
                                textStyle: {
                                    color: '#ADFF2F' // 亮绿色字体
                                }
                            }
                        },
                        grid: {top: '48%'},
                        series: Object.keys(priceDataMap).map(function (year) {
                            return {
                                name: year,
                                type: 'line',
                                data: priceDataMap[year].map(function (item) {
                                    return item.averagePrice;
                                }),
                                smooth: true,
                                emphasis: {focus: 'series'},
                            };
                        }).concat({
                            type: 'pie',
                            id: 'pie',
                            radius: '30%',
                            center: ['50%', '25%'],
                            emphasis: {
                                focus: 'self'
                            },
                            label: {
                                formatter: '{b}: {c} ({d}%)',
                            },
                            encode: {
                                itemName: 'year',
                                value: 'averagePrice',
                                tooltip: 'averagePrice'
                            },
                            data: []
                        })
                    };

                    myChart.setOption(option);

                    myChart.on('updateAxisPointer', function (event) {
                        var xAxisInfo = event.axesInfo[0];
                        if (xAxisInfo) {
                            var dimension = xAxisInfo.value;
                            console.log(dimension)
                            var pieData = Object.keys(priceDataMap).map(function (year) {
                                return {
                                    name: year,
                                    value: priceDataMap[year][dimension].averagePrice
                                };
                            });
                            console.log("pieData")
                            console.log(pieData) //有数据
                            myChart.setOption({
                                series: [{
                                    id: 'pie',
                                    data: pieData
                                }]
                            });
                        }
                    });
                }
            })
        });
        /*]]>*/
    </script>

    <!--    某地区某年所有月份的数据-->
    <!-- 某地区某年所有月份的数据 -->
    <!-- 某地区某年所有月份的数据 -->
<!--    <script th:inline="javascript">-->
<!--        /*<![CDATA[*/-->
<!--        var province = /*[[${province}]]*/ ;-->
<!--        var year = /*[[${year}]]*/ ;-->
<!--            (function() {-->
<!--            // 使用AJAX调用服务器接口-->
<!--            $.ajax({-->
<!--                url: "/test",-->
<!--                type: "GET",-->
<!--                data: {-->
<!--                    province: province,-->
<!--                    year: year-->
<!--                },-->
<!--                success: function (dataList) {-->
<!--                    var myChart = echarts.init(document.querySelector('.bar2 .chart'), 'dark');-->
<!--                    var option = {-->
<!--                        title: {-->
<!--                            text: ''-->
<!--                        },-->
<!--                        tooltip: {-->
<!--                            trigger: 'axis'-->
<!--                        },-->
<!--                        legend: {-->
<!--                            data: ['Price']-->
<!--                        },-->
<!--                        grid: {-->
<!--                            left: '3%',-->
<!--                            right: '4%',-->
<!--                            bottom: '3%',-->
<!--                            containLabel: true-->
<!--                        },-->
<!--                        toolbox: {-->
<!--                            feature: {-->
<!--                                saveAsImage: {}-->
<!--                            }-->
<!--                        },-->
<!--                        xAxis: {-->
<!--                            type: 'category',-->
<!--                            boundaryGap: false,-->
<!--                            // 这里使用月份作为x轴的数据-->
<!--                            data: dataList.map(function (item) {-->
<!--                                return item.month;-->
<!--                            })-->
<!--                        },-->
<!--                        yAxis: {-->
<!--                            type: 'value'-->
<!--                        },-->
<!--                        series: [-->
<!--                            {-->
<!--                                name: 'Price',-->
<!--                                type: 'line',-->
<!--                                // 这里使用价格作为y轴的数据-->
<!--                                data: dataList.map(function (item) {-->
<!--                                    return item.averagePrice;-->
<!--                                })-->
<!--                            }-->
<!--                        ]-->
<!--                    };-->

<!--                    option && myChart.setOption(option);-->
<!--                },-->
<!--                error: function (jqXHR, textStatus, errorThrown) {-->
<!--                    // 异常处理-->
<!--                    console.error(textStatus, errorThrown);-->
<!--                }-->
<!--            });-->
<!--        })();-->
<!--        /*]]>*/-->
<!--    </script>-->

    <!--    动态柱形图-->
    <script th:inline="javascript">
        /*<![CDATA[*/
        var year = /*[[${year}]]*/ ;
        (function() {
            var chartDom = document.querySelector('.line .chart');
            var myChart = echarts.init(chartDom, 'dark');
            var option;
            var updateFrequency = 3000;
            var allData;

            function updateChart(monthData, year, month) {
                var provinces = Object.keys(monthData);
                var prices = provinces.map(function (province) {
                    return monthData[province] || 0;
                });

                option = {
                    xAxis: {
                        type: 'value',
                        max: 'dataMax'
                    },
                    yAxis: {
                        type: 'category',
                        data: provinces,
                        inverse: true
                    },
                    series: [{
                        realtimeSort: true,
                        name: 'price',
                        type: 'bar',
                        data: prices,
                        label: {
                            show: true,
                            formatter: function (params) {
                                return params.value.toFixed(1);
                            }
                        },
                        animationDuration: updateFrequency,
                        animationEasing: 'linear',
                        animationEasingUpdate: 'linear'
                    }],
                    graphic: {
                        elements: [{
                            type: 'text',
                            style: {
                                text: year + ' ' + month + '月',
                                font: 'bolder 80px monospace',
                                fill: 'rgba(100, 100, 100, 0.25)'
                            },
                            right: 0,
                            bottom: 60,
                            z: 100
                        }]
                    }
                };

                myChart.setOption(option, true);
            }

            function fetchAndUpdate() {
                $.ajax({
                    url: '/dynamic_bar_chart',
                    type: 'GET',
                    data: {
                        year: year
                    },
                    success: function (data) {
                        allData = data;
                        console.log("动态柱形图")
                        var months = Object.keys(allData);
                        months.sort();

                        months.forEach((month, index) => {
                            setTimeout(function () {
                                updateChart(allData[month], '2018', month);
                            }, updateFrequency * index);
                        });
                    },
                    error: function (error) {
                        console.log('Error:', error);
                    }
                });
            }

            fetchAndUpdate();
        })();
        /*]]>*/
    </script>

    <!--    南丁玫瑰图-->
    <script th:inline="javascript">
        /*<![CDATA[*/
        var priceDataList2 = /*[[${priceDataList}]]*/ [];
        (function() {
            var myChart = echarts.init(document.querySelector('.line2 .chart'), 'dark');
            var data = priceDataList2.map(priceData => ({
                name: priceData.province,
                value: priceData.averagePrice,
            }));
            var dataName = [];
            for (var name in data) { // 遍历省份
                dataName.push(name); // 该省份价格,若无数据则默认0
            }

            var option = {
                title: {
                    text: 'Nightingale Chart',
                    subtext: 'Fake Data',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                legend: {
                    left: 'center',
                    top: 'bottom',
                    data: dataName
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: false },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                series: [
                    {
                        name: 'Area Mode',
                        type: 'pie',
                        radius: [20, 140],
                        center: ['50%', '50%'],
                        roseType: 'area',
                        itemStyle: {
                            borderRadius: 5
                        },
                        data: data
                    }
                ]
            };
            option && myChart.setOption(option);

        })();
        /*]]>*/
    </script>

    <!--    某省某年某月所有天数的价格变化-->
    <script th:inline="javascript">
        var app = {};

        var chartDom = document.querySelector('.bar2 .chart');
        var myChart = echarts.init(chartDom, 'dark');
        var option;

        const categories = [];
        const data = [];
        const maxPriceData = []; // 新增
        let numberOfDataPointsToShow = 5;

        async function fetchData() {
            const response = await fetch('/data/province/year/month/days?province=广西&year=2018&month=1');
            const priceDataList = await response.json();

            for (let i = 0; i < numberOfDataPointsToShow && i < priceDataList.length; i++) {
                categories.push(priceDataList[i].month + '-' + priceDataList[i].day);
                data.push(priceDataList[i].averagePrice);
                maxPriceData.push(priceDataList[i].maxPrice); // 新增
            }

            updateChart();

            setInterval(function () {
                if (priceDataList.length > numberOfDataPointsToShow) {
                    categories.shift();
                    data.shift();
                    maxPriceData.shift(); // 新增

                    const nextDataPoint = priceDataList.slice(numberOfDataPointsToShow).shift();
                    categories.push(nextDataPoint.month + '-' + nextDataPoint.day);
                    data.push(nextDataPoint.averagePrice);
                    maxPriceData.push(nextDataPoint.maxPrice); // 新增
                    numberOfDataPointsToShow++;

                    updateChart();
                }
            }, 2100);
        }

        function updateChart() {
            myChart.setOption({
                xAxis: {
                    data: categories
                },
                series: [
                    {
                        data: maxPriceData
                    },
                    {
                        data: data
                    }
                ]
            });
        }

        option = {
            title: {
                text: ''
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#283b56'
                    }
                }
            },
            legend: {
                data: ['最高价格', '平均价格']
            },
            toolbox: {
                show: true,
                feature: {
                    dataView: { readOnly: false },
                    restore: {},
                    saveAsImage: {}
                }
            },
            dataZoom: {
                show: false,
                start: 0,
                end: 100
            },
            xAxis: {
                type: 'category',
                boundaryGap: true,
                data: categories
            },
            yAxis: {
                type: 'value',
                scale: true,
                name: 'Price',
                min: 0,
                boundaryGap: [0.2, 0.2]
            },
            series: [
                {
                    name: '最高价格',
                    type: 'bar',
                    data: maxPriceData
                },
                {
                    name: '平均价格',
                    type: 'line',
                    data: data
                }
            ]
        };

        option && myChart.setOption(option);

        fetchData();
    </script>

</body>
</html>